<template>
  <div class="Manage">
    <!-- Dialog 弹出框 -->
    <el-dialog
      :title="
        dialogConfig.openType === 'add'
          ? dialogConfig.addName
          : dialogConfig.editName
      "
      :close-on-click-modal="false"
      :visible.sync="dialogConfig.isShowDialogVisible"
      width="50%"
    >
      <CommonForm
        :form="dialogForm"
        :formLabel="dialogFormLabel"
        :formConfig="dialogFormLConfig">
      </CommonForm>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialogFormData(dialogForm)">确 定</el-button>
        <el-button @click="dialogConfig.isShowDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 主区域 -->
    <CommonManageMain>
      <!-- 主区域（header）：标题、头部按钮 -->
      <template v-slot:header class="header">
        <h3>校区管理</h3>
        <div class="topBtn">
          <el-button type="primary" plain size="medium" @click="clickAddData()"
            >添 加</el-button
          >
          <el-popconfirm
            icon="el-icon-info"
            icon-color="red"
            @confirm="clickDeleteData(tableSelection)"
            :title="
              tableSelection.length == 0
                ? '请选中要删除的记录！'
                : '确定要删除' + tableSelection.length + '条记录吗？'
            "
          >
            <el-button type="danger" slot="reference" size="medium" plain
              >删 除</el-button
            >
          </el-popconfirm>
          <el-button
            icon="el-icon-search"
            size="medium"
            plain
            @click="searchDivVisible = !searchDivVisible"
            >检 索</el-button
          >
          <!-- 显示列 弹出框 -->
          <el-popover placement="bottom-start" width="200" trigger="hover">
            <el-button
              type="info"
              slot="reference"
              plain
              class="showColumnBtn"
              size="medium"
              >显示列</el-button
            >
            <!-- 显示列的多选框 -->
            <el-checkbox-group
              v-model="checkedColumnList"
              @change="handleCheckedColumnChange"
            >
              <el-checkbox
                v-for="item in tableColumnList"
                :label="item.label"
                :key="item.label"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </el-popover>
          <!-- 检索部表单部分 -->
          <transition name="el-collapse-transition">
            <div class="searchDiv" v-if="searchDivVisible">
              <CommonForm
                :form="searchForm"
                :formLabel="searchFormLabel"
                :formConfig="searchFormLConfig"
              >
              </CommonForm>
              <el-button
                type="primary"
                size="mini"
                @click="clickToSearch(searchForm)"
                >搜 索</el-button
              >
              <el-button type="danger" size="mini" @click="clicResetForm()"
                >重 置</el-button
              >
            </div>
          </transition>
        </div>
      </template>
      <!-- 主区域（content）：表格部分 -->
      <template v-slot:content class="content">
        <CommonTable
          :tableData="tableData"
          :tableLabel="tableLabel"
          :tableConfig="tableConfig"
          @handleSelectionChange="handleSelectionChange"
          @sizeChange="getTableData(1, tableConfig.size, {})"
          @currentPage="getTableData(tableConfig.page, tableConfig.size, {})"
        >
          <template v-slot:operation>
            <el-table-column prop="operation" label="操作">
              <template slot-scope="scope">
                <el-tooltip
                  :enterable="false"
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                >
                  <el-button
                    type="primary"
                    size="mini"
                    @click="clickEditData(scope.row)"
                    >编辑</el-button
                  >
                </el-tooltip>
              </template>
            </el-table-column>
          </template>
        </CommonTable>
      </template>
    </CommonManageMain>
  </div>
</template>

<script>
import CommonManageMain from "components/common/CommonManageMain.vue";
import CommonTable from "components/common/CommonTable.vue";
import CommonForm from "components/common/CommonForm.vue";
import { TextToCode, CodeToText } from 'element-china-area-data'
import { getProviderNameId } from "api/systemManage/organizationManage.js"
import {
  getCampusList,
  addCampus,
  editCampus,
  deleteCampus,
  getCampusInfo
} from "api/schoolManage/campusManage.js";

export default {
  name: "campusMansge",
  components: {
    CommonManageMain,
    CommonTable,
    CommonForm
  },
  data() {
    return {
      // ...........表格...........
      // 表格 数据
      tableData: [],
      // 表格 列表
      tableLabel: [
        {
          prop: "schoolName",
          label: "学校名称",
          width:'70'
        },
        {
          prop: "campusName",
          label: "校区名称",
          width:'70'

        },
        {
          prop: "campusAddress",
          label: "校区地址",
          width:'70'
        },
        {
          prop: "contactPerson",
          label: "联系人",
          width:'70'
        },
        {
          prop: "phone",
          label: "电话",
          width:'70'
        },
        {
          prop: "providerName",
          label: "服务商",
          width:'70'
        },
        {
          prop: "providerPhone",
          label: "服务商电话",
          width:'70'
        }
      ],
      // 表格 自定义配置
      tableConfig: {
        // 是否显示分页
        isShowLoading: true,
        page: 1,
        total: 30,
        size: 10,
        // 加载状态
        loading: false,
        // 显示 选择多行数据
        selection: true,
        rowKey: "campusId"
      },
      // 表格选中记录的列表
      tableSelection: [],
      // 表格 列的集合
      tableColumnList: [],
      // 显示列 已选中集合
      checkedColumnList: [],

      // ...........Dialog...........
      // Dialog 表单数据
      dialogForm: {
        campusAddress: "",
        campusName: "",
        contactPerson: "",
        email: "",
        fax: "",
        logo: "",
        phone: "",
        providerId: "",
        schoolName: "",
        provinceCityArea: ""
      },
      // Dialog 表单字段
      dialogFormLabel: [
        {
          model: "schoolName",
          label: "学校名称",
          width: "60",
          rules: [
            {required: true, message: '请输入学校名称', trigger: 'blur'}
          ]
        },
        {
          model: "campusName",
          label: "校区名称",
          width: "60"
        },
        {
          model: "provinceCityArea",
          type: "cascaderArea",
          label: "所在地区"
        },
        {
          model: "campusAddress",
          type: "textarea",
          rows: 4,
          label: "请输入详细地址，最多50位字符，支持数字、字母、下划线、汉字",
          labelOFF: "off",
          width: "66"
        },
        {
          model: "contactPerson",
          label: "联系人",
          width: "60"
        },
        {
          model: "phone",
          label: "联系电话",
          width: "60"
        },
        {
          model: "fax",
          label: "传真",
          width: "60"
        },
        {
          model: "email",
          label: "邮箱",
          width: "60"
        },
        {
          model: "logo",
          label: "校区Logo",
          type: "upload",
          imgType: 1
        },
        {
          model: "providerId",
          label: "服务商",
          type: "select",
          options:[]
        }
      ],
      // Dialog 表单自定义属性
      dialogFormLConfig: {
        labelWidth: "100px",
        inline: false,
        labelPosition: "right"
      },
      // Dialog 自定义属性
      dialogConfig: {
        openType: "add",
        addName: "添加",
        editName: "编辑",
        isShowDialogVisible: false
      },
      // ...........searchDiv 检索部分...........
      // 检索部分 显示状态
      searchDivVisible: false,
      // 检索部分 表单数据
      searchForm: {
        campusName: "",
        contactPerson: "",
        phone: "",
        provider: "",
        providerPhone: "",
        schoolName: ""
      },
      // 检索部分 表单
      searchFormLabel: [
        {
          model: "schoolName",
          label: "学校名称"
        },
        {
          model: "campusName",
          label: "校区名称"
        },
        {
          model: "provider",
          label: "服务商"
        },
        {
          model: "contactPerson",
          label: "联系人"
        },
        {
          model: "phone",
          label: "联系人电话"
        },
        {
          model: "providerPhone",
          label: "服务商电话"
        }
      ],
      // 检索部分 表单自定义属性
      searchFormLConfig: {
        labelWidth: "100px",
        inline: true,
        labelPosition: "left"
      },
    };
  },
  beforeMount() {
    //初始化 显示列 的数据
    this.tableColumnList = this.tableLabel;
    this.checkedColumnList = this.tableColumnList.map(item => {
      return item.label;
    });
    //初始化 表格数据
    this.getTableData(1, this.tableConfig.size, {});
    //初始化 服务商的下拉框选项
    getProviderNameId().then( res => {
      const resData = res.data
      if(resData.code == 200) {
          this.dialogFormLabel[9].options = resData.data.map( item => {
            return {
              id: item.providerId,
              label: item.providerName
            }
          })
      }
    })

  },
  watch:{
    // 当 dialog 关闭时 ，刷新表单
    'dialogConfig.isShowDialogVisible' (newValue, oldValue) {
      if(!newValue) {
        this.dialogForm =  this.$options.data().dialogForm
      }
    }
  },
  methods: {

    // 添加操作
    clickAddData() {
      this.dialogConfig.openType = 'add'
      this.dialogConfig.isShowDialogVisible = true;
    },

    // 删除操作
    clickDeleteData(val) {
      if (val.length > 0) {
        const deleteList = val.map(item => {
          return this.deleteCampus(item.campusId);
        });
        Promise.all(deleteList)
          .then(() => {
            this.$message({
              message: "成功删除" + deleteList.length + "条记录",
              type: "success"
            });
            //初始化表格数据
            this.getTableData(1, this.tableConfig.size, {});
          })
          .catch(() => {
            //错误处理
          });
      }
    },

    // 搜索按钮
    clickToSearch(searchForm) {
      let DATA = {};
      //过滤需要搜索的字段
      for (let i in searchForm) {
        if (searchForm[i] != "") {
          DATA[i] = searchForm[i];
        }
      }
      this.getTableData(1, this.tableConfig.size, DATA);
    },

    // 重置检索表单
    clicResetForm() {
      // 初始化 searchForm
      this.searchForm = this.$options.data().searchForm;
    },

    // 编辑按钮
    clickEditData(row) {
      const campusId = row.campusId;
      getCampusInfo(campusId).then(res => {
        const resData = res.data;
         if(resData.code ==200) {
           this.dialogForm = {
              campusId:resData.data.campusId,
              campusAddress: resData.data.campusAddress,
              campusName: resData.data.campusName,
              contactPerson: resData.data.contactPerson,
              email: resData.data.email,
              fax: resData.data.fax,
              logo: resData.data.logo,
              phone: resData.data.phone,
              providerId: resData.data.providerId,
              schoolName: resData.data.schoolName,
              // provinceCityArea: this.AreaFormatCode(resData.data.provinceCityArea)
           }
           this.dialogConfig.isShowDialogVisible = true
           this.dialogConfig.openType = 'edit'
         }
      });
    },

    // dialog 表单数据提交 新增、编辑校区
    submitDialogFormData(formData) {
      // add: 新增  、 edit: 编辑
      const type = this.dialogConfig.openType
      if(type == 'add'){
        const DATA = {
          campusAddress: formData.campusAddress,
          campusName: formData.campusName,
          contactPerson: formData.contactPerson,
          email: formData.email,
          fax: formData.fax,
          logo: 'url',//formData.log,待完善...
          phone: formData.phone,
          providerId: formData.providerId,
          schoolName: formData.schoolName,
          provinceCityArea: this.AreaFormatText(formData.provinceCityArea)
        }
        addCampus(DATA).then( res => {
          const resData = res.data
          if(resData.code == 200) {
            this.$message({
              message: resData.message,
              type: 'success'
            })
            // 刷新 Table 的数据
            this.getTableData(1, this.tableConfig.size, {});
            this.dialogConfig.isShowDialogVisible = false
          }else{
            this.$message({
              message: resData.message,
              type: 'error'
            })
          }

        })

      }else{
        const DATA = {
          campusAddress: formData.campusAddress,
          campusName: formData.campusName,
          contactPerson: formData.contactPerson,
          email: formData.email,
          fax: formData.fax,
          logo: 'url',//formData.log,待完善...
          phone: formData.phone,
          providerId: formData.providerId,
          schoolName: formData.schoolName,
          provinceCityArea: this.AreaFormatText(formData.provinceCityArea)
        }
         editCampus(formData.campusId, DATA).then( res => {
           const resData = res.data
          if(resData.code == 200) {
            this.$message({
              message: resData.message,
              type: 'success'
            })
            // 刷新 Table 的数据
            this.getTableData(1, this.tableConfig.size, {});
            this.dialogConfig.isShowDialogVisible = false
          }else{
            this.$message({
              message: resData.message,
              type: 'error'
            })
          }
         })
      }

    },
    // 显示列 选择事件
    handleCheckedColumnChange() {
      this.tableLabel = this.tableColumnList.filter(columnItem => {
        let isTrue = false;
        for (let checkedcolumnItem of this.checkedColumnList) {
          if (checkedcolumnItem === columnItem.label) {
            isTrue = true;
          }
        }
        return isTrue;
      });
    },
    // 表格选择事件
    handleSelectionChange(val) {
      this.tableSelection = val;
    },
    // Text To Code
    AreaFormatCode(val = "[广东省,东莞市,寮步镇]") {
      // val : "[广东省,东莞市,寮步镇]"
      // result: ['440000', '441900', '441900111']
      let arr, result = [];
      arr =  val.replace("[","").replace("]","").split(",")
      result.push(TextToCode[arr[0]].code)
      result.push(TextToCode[arr[0]][arr[1]].code)
      result.push(TextToCode[arr[0]][arr[1]][arr[2]].code)
      return result
    },
    // Code To Text
    AreaFormatText(val){
      // val: ['440000', '441900', '441900111']
      // result: "[广东省,东莞市,寮步镇]"
      let result;
      if(val.length > 0 && val instanceof Array) {
        result = val.map( code => {
          return CodeToText[code]
        })
      }
      return result.join(',')
    },
    // 获取学校信息列表
    getTableData(page, pageSize, datas) {
      getCampusList(page, pageSize, datas).then(res => {
        const resData = res.data;
        if (resData.code == 200) {
          this.tableData = resData.data.records;
          const dataList = this.tableData.length
          this.$message({
            message: dataList == 0 ? '没有符合的角色名' : '成功搜索到 ' + dataList + " 条数据",
            type: 'success'
          })
          this.tableConfig.total = resData.data.total;
        }
      });
    },
    // 删除校区信息
    deleteCampus(id) {
      return new Promise(((resolve,reject) => {
        deleteCampus(id).then(res => {
          if (res.data.code == 200) {
            resolve();
          }else {
            reject()
          }
        });
      }));
    }
  }
};
</script>

<style lang="scss" scoped>
.Manage {
  height: 100%;
  overflow: hidden;
  .topBtn {
    width: 100%;
    margin: 10px 0;
    position: relative;
    > * {
      // 选中topBtn所有子元素
      margin-right: 10px;
    }
    .showColumnBtn {
      position: absolute;
      right: 0;
    }
    .searchDiv {
      margin-top: 10px;
    }
  }
}
</style>
